import { _decorator, Component, EditBox, Node } from 'cc';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import VillageApi from '../api/VillageApi';
import { MapZone } from '../entity/MapZone';
import WorldManager from '../common/WorldManager';
import { Village } from '../entity/Village';
import { ComfirmVillage } from './ComfirmVillage';
const { ccclass, property } = _decorator;

@ccclass('SelectCoord')
export class SelectCoord extends Component {
    @property(Node)
    close:Node
    @property(EditBox)
    xInput:EditBox
    @property(EditBox)
    yInput:EditBox
    @property(Node)
    submit:Node

    start() {
        this.close.on(Node.EventType.TOUCH_END, this.onClose, this)
        this.submit.on(Node.EventType.TOUCH_END, this.onSubmit, this)
    }

    onClose(){
        UIManager.instance.closeUI(PrefabEnum.SelectCoord)
    }

    async onSubmit(){
        let x = this.xInput.string
        let y = this.yInput.string

        if(!/^-?\d+$/.test(x)){
            UIManager.instance.tip('请输入正确的坐标')
            return
        }
        if(!/^-?\d+$/.test(y)){
            UIManager.instance.tip('请输入正确的坐标')
            return
        }

        let coordX = parseInt(x)
        let coordY = parseInt(y)

        if(coordX < -400 || coordX > 400){
            UIManager.instance.tip('请输入正确的坐标')
            return
        }
        if(coordY < -400 || coordY > 400){
            UIManager.instance.tip('请输入正确的坐标')
            return
        }

        let zoneId = MapZone.getZoneIdByXy(coordX, coordY, WorldManager.instance.radius)
        await UIManager.instance.showLoading()
        let res = await VillageApi.queryThird(zoneId)
        UIManager.instance.closeLoading()
        console.log(`查找村庄x=${coordX},y=${coordY},zoneId=${zoneId}：`, res)

        let village = Village.createByVillageObj(res.data)
        console.log(village)
        if(village.uid == 0){
            UIManager.instance.tip('没有找到村庄')
            return
        }

        let ui = await UIManager.instance.openUI(PrefabEnum.ComfirmVillage)
        ui.getComponent(ComfirmVillage).setData(village)
    }
}


